#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
数据库初始化脚本
创建初始用户和基础数据
"""

import os
import sys
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import create_app
from models import db, User, Problem, Homework, Course
from utils import hash_password

def init_database():
    """初始化数据库"""
    app = create_app()
    
    with app.app_context():
        try:
            # 创建所有表
            db.create_all()
            print("✅ 数据库表创建成功")
            
            # 检查是否已有数据
            if User.query.first():
                print("⚠️  数据库中已有数据，跳过初始化")
                return
            
            # 创建管理员用户
            admin_user = User(
                username='admin',
                email='admin@ojsystem.com',
                password_hash=hash_password('admin123'),
                role='admin',
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            db.session.add(admin_user)
            
            # 创建教师用户
            teacher_user = User(
                username='teacher',
                email='teacher@ojsystem.com',
                password_hash=hash_password('teacher123'),
                role='teacher',
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            db.session.add(teacher_user)
            
            # 创建学生用户
            student_user = User(
                username='student',
                email='student@ojsystem.com',
                password_hash=hash_password('student123'),
                role='student',
                level='beginner',
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            db.session.add(student_user)
            
            # 创建示例题目
            problem1 = Problem(
                title='Hello World',
                description='编写一个程序输出"Hello World"',
                type='code',
                difficulty='easy',
                language='python',
                test_cases='[{"input": "", "output": "Hello World"}]',
                created_by=teacher_user.id,
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            db.session.add(problem1)
            
            problem2 = Problem(
                title='两数之和',
                description='给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出和为目标值 target 的那两个整数，并返回它们的数组下标。',
                type='code',
                difficulty='medium',
                language='python',
                test_cases='[{"input": "[2,7,11,15]\\n9", "output": "[0,1]"}]',
                created_by=teacher_user.id,
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            db.session.add(problem2)
            
            # 创建示例作业
            homework1 = Homework(
                title='第一次作业 - 基础编程',
                description='完成基础编程练习，包括Hello World和简单计算',
                problems=[problem1.id, problem2.id],
                deadline=datetime(2024, 12, 31, 23, 59, 59),
                teacher_id=teacher_user.id,
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            db.session.add(homework1)
            
            # 创建示例课程
            course1 = Course(
                name='Python编程基础',
                description='学习Python编程语言的基础知识和应用',
                teacher_id=teacher_user.id,
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            db.session.add(course1)
            
            # 提交所有更改
            db.session.commit()
            
            print("✅ 数据库初始化成功！")
            print("\n📋 初始用户账号：")
            print("👨‍💼 管理员 - 用户名: admin, 密码: admin123")
            print("👨‍🏫 教师 - 用户名: teacher, 密码: teacher123")
            print("👨‍🎓 学生 - 用户名: student, 密码: student123")
            print("\n📝 示例数据：")
            print("- 2个编程题目")
            print("- 1个作业")
            print("- 1个课程")
            
        except Exception as e:
            print(f"❌ 数据库初始化失败: {e}")
            db.session.rollback()
            raise

if __name__ == '__main__':
    print("🚀 开始初始化数据库...")
    init_database()
    print("🎉 数据库初始化完成！")
